import { _decorator, Label, ProgressBar } from 'cc';
import { LayerType, RepelType } from '../Config/BaseEnum';
import { PanelBase } from './PanelBase';
import { LoadingManager } from '../Manager/LoadingManager';
import { LayerManager } from '../Manager/LayerManager';
import { CallBackHandler } from '../Model/PoolObj/CallBackHandler';
const { property } = _decorator;
export class LoadPanelBase extends PanelBase {
  panelLayer: LayerType.LoadingLayer = LayerType.LoadingLayer;
  panelRepelType: RepelType = RepelType.None;

  @property(ProgressBar)
  bar: ProgressBar = null!;
  @property(Label)
  barLab: Label = null!;
  @property
  speed: number = 1;
  @property
  toFixed: number = 0;

  protected tempRate: number = 0;
  protected loadingRate: number = 0;
  protected saveProp: Record<any, any> | null = null;
  loadPanel(resPath: string, prop?: Record<any, any>): void {
    this.saveProp = prop;
    try {
      const res = LoadingManager.Ins().getResource(resPath);
      this.onComplete([res]);
    } catch {
      this.tempRate = 0;
      this.loadingRate = 0;
      this.bar.progress = 0;
      this.barLab.string = '0%';
      this.node.active = true;
      LoadingManager.Ins().loadResource(
        resPath,
        this.onProgress,
        CallBackHandler.pop(
          CallBackHandler.pop((res) => {
            this.onComplete(res);
          }, this),
          this
        )
      );
    }
  }

  protected update(dt: number): void {
    // if (this.tempRate < this.loadingRate) {
    //   this.tempRate += dt * this.speed;
    //   if (this.tempRate > this.loadingRate) {
    //     this.tempRate = this.loadingRate;
    //     this.node.active = false;
    //   }
    // } else {
    //   return;
    // }
    // const rate = this.tempRate / this.loadingRate;
    // this.barLab.string = `${(rate * 100).toFixed(this.toFixed)}%`;
    // this.bar.progress = rate > 1 ? 1 : rate;
  }

  protected onProgress(rate) {
    // this.loadingRate = rate;
  }

  protected onComplete(res): void {
    LayerManager.Singleton.loadPanelComplete(res, this.saveProp);
    this.saveProp = null;
    // this.node.active = false;
  }
}
